//
//	File Name   :	TextureManager.cpp
//	Description :	TextureManager implementation file.
//	Author		:	William McVicar
//  Mail		:	mcvicar.william@gmail.com
//

//  Precompiled Header
#include "CommonDefines.h"

//  Library Includes

//  Local Includes
#include "TextureBase.h"
#include "Texture2D.h"

//  This includes
#include "TextureManager.h"

//	Macros

//  Static Variables

//  Static Function Prototypes

//  Implementation

namespace Protein
{

TextureManager::~TextureManager()
{
	u32 numTextures = m_textureMap->quantity();
	u32 nukedTextures = 0;
	for( u32 i = 0; i < m_textureMap->tableSize(); ++i )
	{
		TEXTUREMAP::HashItem* item = (*m_textureMap)[i];
		if( !item )
			continue;

		while( item )
		{
			++nukedTextures;
			delete item->m_Value;
			item = item->m_pNext;
		}

		if( nukedTextures == numTextures )
			break;
	}

	delete m_textureMap;
	m_textureMap = NULL;
}

Texture2D* TextureManager::create( const char* szName )
{
	Texture2D* tex = m_textureMap->find( szName );
	if( tex )
		return tex;

	TextureBase* base = new TextureBase( szName );
	assert( base->Load() && "Error: Couldn't load Texture" );

	tex = new Texture2D( base );
	++tex->m_textureBase->m_referenceCount;
	m_textureMap->insert( szName, tex );
	return tex;
}

void TextureManager::free( const char* szName )
{
	Texture2D* tex = m_textureMap->find( szName );
	if( !tex )
		return;

	if( --tex->m_textureBase->m_referenceCount == 0 )
	{
		delete tex;
		m_textureMap->remove( szName );
	}
}

}